/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servergui;

import DataObject.TableObject;
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableColumn;

/**
 *
 * @author Backkom
 */
public class DesignView extends JPanel implements ListSelectionListener, KeyListener {
    /*
     * To change this template, choose Tools | Templates and open the template
     * in the editor.
     */

    public String tableName;
    public String databaseName;
    protected JTable tables;
    RowHeader rowHD;
    protected MainScreen frameParent;
    protected TableValues values;
    protected Vector<TableObject> listObject;
    protected String[] tbHeader;
    protected boolean isKeepCtrl = false;    
    protected JTextArea Output;
    boolean Saved = true;
    boolean isNew = true;
    JFileChooser fc = new JFileChooser();
    int[] SelectIndex = null;
    int Action = 0;

    public DesignView(MainScreen parent, String dbName, String tbName, Vector<TableObject> listData, boolean iNew) {
        super(true);
        tbHeader = new String[]{"Column Name", "Data Type", "Primary Key"};
        isNew = iNew;
        listObject = new Vector<TableObject>();
        listObject.addAll(listData);
        frameParent = parent;
        tableName = tbName;
        databaseName = dbName;
        this.setLayout(new BorderLayout());
        this.addKeyListener(this);
        values = new TableValues(listObject, tbHeader, this, null);
        tables = new JTable();
        tables.addKeyListener(this);
        InitTable();
    }

    public void UpdateTable() {
        for (int i = 0; i < listObject.size();) {
            Object obj = listObject.elementAt(i).getAttributeAt(0);
            if (obj != null && obj.toString().compareToIgnoreCase("X") == 0) {
                listObject.removeElementAt(i);
                continue;
            } else {
                i++;
            }
        }
        values = new TableValues(listObject, tbHeader, this, null);
        tables.setModel(values);
        tables.paintAll(tables.getGraphics());
    }

    private void InitTable() {
        tables.setModel(values);
        tables.setShowGrid(true);
        tables.setDoubleBuffered(true);
        tables.setColumnSelectionAllowed(false);
        tables.setRowSelectionAllowed(true);
        tables.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        tables.getSelectionModel().addListSelectionListener(this);
        setRendererCombobox();
        tables.addFocusListener(new FocusAdapter() {

            @Override
            public void focusLost(FocusEvent e) {
                tables.clearSelection();
                super.focusLost(e);
            }
        });
        tables.addComponentListener(new TableScroller());
        JScrollPane scroll = new JScrollPane(tables);
        JViewport jvp = new JViewport();
        rowHD = new RowHeader(tables, values);
        jvp.setView(rowHD);
        scroll.setRowHeader(jvp);
        scroll.addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e) {
                tables.clearSelection();
            }
        });

        this.add(scroll, BorderLayout.CENTER);
        scroll.paintAll(scroll.getGraphics());
    }

    private void deleteRow() {
        if (SelectIndex != null && SelectIndex.length > 0) {
            for (int i = 0; i < SelectIndex.length; i++) {
                listObject.elementAt(SelectIndex[i]).setAttributeAt(0, "X");
            }
            UpdateTable();
        }
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (e.getSource() == tables.getSelectionModel()) {
            SelectIndex = tables.getSelectedRows();
            if (Saved) {
                Saved = false;
                frameParent.Update(tableName, Saved);
            }
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_CONTROL: {
                isKeepCtrl = true;
            }
            break;
            case KeyEvent.VK_ENTER: {
                values.addLine();
                rowHD.values.fireTableDataChanged();
            }
            break;
            case KeyEvent.VK_S: {
                if (isKeepCtrl) {
                    frameParent.SaveDesign(databaseName, tableName, listObject, isNew);
                    Saved = true;
                    frameParent.Update(tableName, Saved);
                }
            }
            break;
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
            isKeepCtrl = false;
        }
    }

    private void setRendererCombobox() {
        if (tbHeader.length > 1) {
            TableColumn typeColumn = tables.getColumnModel().getColumn(1);
            JComboBox comboBox = new JComboBox();
            comboBox.addItem("String");
            comboBox.addItem("Integer");
            typeColumn.setCellEditor(new DefaultCellEditor(comboBox));
        } else {
            tables.setCellEditor(new DefaultCellEditor(new JTextField()));
        }
    }

    boolean Exits() {
        int rs = JOptionPane.NO_OPTION;
        if (!Saved) {
            rs = JOptionPane.showConfirmDialog(frameParent, "Do you want to save this design", "Save data", JOptionPane.YES_NO_CANCEL_OPTION);
        }
        if (rs == JOptionPane.CANCEL_OPTION) {
            return false;
        }
        if (rs == JOptionPane.YES_OPTION) //Save Design
        {
            frameParent.SaveDesign(databaseName, tableName, listObject, isNew);
        }
        return true;
    }

    class TableScroller extends ComponentAdapter {

        @Override
        public void componentResized(ComponentEvent event) {
            int lastRow = listObject.size() - 1;
            int cellTop = tables.getCellRect(lastRow, 0, true).y;
            JScrollPane jsp = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, tables);
            JViewport jvp = jsp.getViewport();
            int portHeight = jvp.getSize().height;
            int position = cellTop - (portHeight - tables.getRowHeight() - tables.getRowMargin());
            if (position >= 0) {
                jvp.setViewPosition(new Point(0, position));
            }
        }
    }
}
